package com.heima.mobile.task;

import cn.hutool.core.collection.CollectionUtil;
import com.heima.pojo.Orders;
import com.heima.pojo.TotalData;
import com.heima.service.OrdersService;
import com.heima.service.TotalDataService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author itheima
 * @since 2022-12-05
 */
@Slf4j
@Component
public class TestTask {

    @Autowired
    private OrdersService ordersService;

    @Autowired
    private TotalDataService totalDataService;

    @Scheduled(fixedRate = 1000)
    public void test() {

        // 1. 查询出订单表中，今日的所有数据
        List<Orders> ordersListByToday = ordersService.getOrdersListByToday();

        System.out.println(ordersListByToday);
        if (CollectionUtil.isEmpty(ordersListByToday)) {
            log.info("今天没有销售数据");
            return;
        }

        // 2. 计算所有数据总金额
        BigDecimal total = new BigDecimal(0);
        for (Orders orders : ordersListByToday) {
            if (orders == null) {
                continue;
            }

            total.add(orders.getAmount());
        }

        // 3. 把总金额存到另外一张汇总表
        TotalData totalData = new TotalData();
        totalData.setTotal(total);

        // 获取当前时间，不包含时分秒
        String now = LocalDate.now().toString();

        totalData.setTime(now);
        try {
            totalDataService.addOne(totalData);
        } catch (DuplicateKeyException e) {
            log.info("出现重复数据");
        }

        log.info("数据统计完毕");
    }
}
